const express = require('express');
const router = express.Router();
const MySQL = require('../../mysql/mysql');
const Log = require('../../common/log');
const bodyParser = require('body-parser');
const MD5 = require('md5');
const Common = require("../../common/common");
const ResList = require('../../common/responseList');

// 配置body-parser
router.use(bodyParser.urlencoded({
    extended: true
}));
router.use(bodyParser.json());

/**
 * 忘记密码
 * 输入原始密码 新密码 
 * 返回修改密码结果
 */
router.post('/updatepassword.node', (req, res) => {
    // 存储客户端传入的数据
    let updateData = {
        UserName: req.body.UserName,
        oldPassword: MD5(req.body.PassWord),
        newPassword: MD5(req.body.newPassword)
    }

    // 检验是否含有客户端传入的空数据
    if (updateData.UserName && updateData.oldPassword && updateData.newPassword) {
        // 检验客户端传入的原始密码是否与当前用户名保存的密码完全相同
        let sql = "select Password from t_user where UserName = " + MySQL.mysql.escape(updateData.UserName);
        MySQL.Mysql(sql, (err, results, fields) => {
            if (err) {
                throw err;
                // 响应客户端
                ResList.ResList(req, res, '1', '修改密码失败', {});
                // 记录日志
                Log.Log4j(Common.getClientIp(req).substring(7), Common.dateFormat(), req.path.substring(1), '1', '修改密码失败','');
            } else {
                if (results[0].Password === updateData.oldPassword) {
                    // 存储需要更新的数据
                    let updatesql = [updateData.newPassword, updateData.UserName];
                    MySQL.Mysql('Update t_user set Password = ? where UserName = ?', updatesql, (err, result, field) => {
                        if (err) {
                            throw err;
                            // 响应客户端
                            ResList.ResList(req, res, '1', '修改密码失败', {});
                            // 记录日志
                            Log.Log4j(Common.getClientIp(req).substring(7), Common.dateFormat(), req.path.substring(1), '1', '修改密码失败','');
                        } else {
                            // 响应客户端
                            ResList.ResList(req, res, '0', '密码修改成功', {});
                            // 记录日志
                            Log.Log4j(Common.getClientIp(req).substring(7), Common.dateFormat(), req.path.substring(1), '0', '密码修改成功','');
                        }
                    })
                } else {
                    // 响应客户端
                    ResList.ResList(req, res, '-3', '原始密码错误', {});
                    // 记录日志
                    Log.Log4j(Common.getClientIp(req).substring(7), Common.dateFormat(), req.path.substring(1), '-3', '原始密码错误','');
                }
            }
        })
    } else {
        // 响应客户端
        ResList.ResList(req, res, '-2', '空指针异常', {});
        // 记录日志
        Log.Log4j(Common.getClientIp(req).substring(7), Common.dateFormat(), req.path.substring(1), '-2', '空指针异常','');
    }
})

module.exports = router;